package dbmanager.connectionManager.menu;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JDialog;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import dbmanager.connectionManager.TreeModel;
import dbmanager.struct.ConnectionFolder;

public class AddFolderItem extends JMenuItem implements ActionListener {

	private JTree tree;

	public AddFolderItem(JTree tree) {
		super("Connection Folder");
		this.tree = tree;
		addActionListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		DefaultMutableTreeNode parent;
		if (!tree.isSelectionEmpty()) {
			TreePath path = tree.getSelectionPath();
			parent = (DefaultMutableTreeNode) path.getLastPathComponent();
		} else {
			parent = (DefaultMutableTreeNode) tree.getModel().getRoot();
		}
		String newFolderName = JOptionPane.showInputDialog(this, "Name of the new folder:", "Create new folder", JOptionPane.PLAIN_MESSAGE);
		ConnectionFolder newFolder = new ConnectionFolder();
		newFolder.setFoldername(newFolderName);
		((TreeModel) tree.getModel()).addFolder(newFolder, parent);
		expandTree();
	}

	private void expandTree() {
		for (int i = 0; i < tree.getRowCount(); i++) {
			tree.expandRow(i);
		}
	}
}
